<!-- 角色列表 -->
<template>
  <div class="">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/rights' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <!-- 添加 -->
        <el-col :span="4">
          <el-button
            type="primary"
            @click="isAddRoles = true"
            class="add_roles"
          >
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="RolesList" style="width: 100%" stripe border>
        <!-- 展开列 -->

        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(tag, index) in scope.row.children"
              :key="tag.id"
              :class="['bottom_border', index === 0 ? 'top_border' : '']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="6">
                <el-tag closable @close="removeRoles(scope.row, tag.id)">
                  {{ tag.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="18">
                <el-row
                  v-for="(itemtag, index) in tag.children"
                  :key="itemtag.id"
                  :class="[index === 0 ? '' : 'top_border']"
                >
                  <el-col :span="8">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRoles(scope.row, itemtag.id)"
                    >
                      {{ itemtag.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <!-- 渲染三级权限 -->
                    <el-row>
                      <el-col :span="24">
                        <el-tag
                          type="warning"
                          closable
                          v-for="threetag in itemtag.children"
                          :key="threetag.id"
                          @close="removeRoles(scope.row, threetag.id)"
                        >
                          {{ threetag.authName }}
                        </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <p class="space_power" v-if="scope.row.children.length == 0">
              暂无权限数据...
            </p>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <!--作用域插槽 -->
            <!-- {{ scope.row }} -->
            <!-- {{ scope.row }}可以取到当前列表项数据 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="EditRoles(scope.row.id)"
              size="mini"
            >
              编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="romoveRoles(scope.row.id)"
              size="mini"
              >删除</el-button
            >
            <el-tooltip content="分配权限" placement="top" :enterable="false">
              <el-button
                type="info"
                icon="el-icon-setting"
                size="mini"
                @click="distributionPower(scope.row)"
                >分配权限
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="isAddRoles"
      width="50%"
      @close="addRolesClose"
    >
      <span class="dialog_input_box">
        <el-form
          ref="rolesInfoRef"
          :model="rolesInfo"
          :rules="editRolesInfoRules"
          label-width="80px"
        >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="rolesInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色职责" prop="roleDesc">
            <el-input v-model="rolesInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddRoles = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="isEditRoles"
      width="50%"
      @close="editRolesClose"
    >
      <span class="dialog_input_box">
        <el-form
          ref="editRolesInfoRef"
          :model="editRolesInfo"
          :rules="editRolesInfoRules"
          label-width="80px"
        >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="editRolesInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色职责" prop="roleDesc">
            <el-input v-model="editRolesInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditRoles = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="isDistributionPower"
      width="50%"
      @close="distributionPowerClose"
    >
      <el-tree
        ref="treeCheckdRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        :data="allPowerData"
        :props="defaultProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDistributionPower = false">取 消</el-button>
        <el-button type="primary" @click="submitDistributionPower"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
  getRolesList,
  addRoles,
  queryRolesId,
  saveEditRoles,
  removeRoles,
  removeRolesPower,
  getAllPower,
  putDistributionPower,
} from "../../service/roles";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      RolesList: [],
      isAddRoles: false,
      isEditRoles: false,
      isDistributionPower: false,
      rolesInfo: {
        roleName: "",
        roleDesc: "",
      },
      editRolesInfo: {
        roleName: "",
        roleDesc: "",
      },
      roleId: "", //分配权限选中的角色ID
      allPowerData: [], //所有权限数据
      defaultProps: {
        children: "children",
        label: "authName",
      }, //树形结构数据
      defKeys: [], //默认展示树型数据
      rolesInfoRules: {
        //添加用户的表单验证
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色职责", trigger: "blur" },
          { min: 2, max: 12, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
      },
      editRolesInfoRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色职责", trigger: "blur" },
          { min: 2, max: 12, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getRolesListFile() {
      getRolesList().then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取数据失败！");
        this.RolesList = res.data;
      });
    },
    //添加角色提交
    submitAddRoles() {
      this.$refs.rolesInfoRef.validate((valid) => {
        if (valid) {
          addRoles(this.rolesInfo).then((res) => {
            if (res.meta.status !== 201)
              return this.$message.error("添加失败！");
            this.getRolesListFile();
            this.isAddRoles = false;
            this.$message.success("添加成功！");
          });
        } else {
          return;
        }
      });
    },

    // 根据ID查询角色信息
    EditRoles(id) {
      this.isEditRoles = true;
      queryRolesId(`roles/${id}`).then((res) => {
        if (res.meta.status !== 200) return this.$message.error("查询失败！");
        this.editRolesInfo = res.data;
        console.log(111111, this.editRolesInfo);
      });
    },
    // 编辑角色提交
    submitEditRoles() {
      this.$refs.editRolesInfoRef.validate((valid) => {
        if (valid) {
          saveEditRoles(`roles/${this.editRolesInfo.roleId}`, {
            roleName: this.editRolesInfo.roleName,
            roleDesc: this.editRolesInfo.roleDesc,
          }).then((res) => {
            if (res.meta.status !== 200)
              return this.$message.error("编辑失败！");
            this.getRolesListFile();
            this.isEditRoles = false;
            this.$message.success("编辑成功！");
          });
        } else {
          return;
        }
      });
    },
    // 删除角色
    romoveRoles(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeRoles(`roles/${id}`).then((res) => {
            if (res.meta.status !== 200)
              return this.$message.error("删除失败！");
            this.getRolesListFile();
            this.$message.success("删除成功！");
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除权限
    removeRoles(role, rigthId) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeRolesPower(`roles/${role.id}/rights/${rigthId}`).then((res) => {
            if (res.meta.status !== 200)
              return this.$message.error("删除失败！");
            role.children = res.data;
            this.$message.success("删除成功！");
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配权限
    distributionPower(role) {
      this.roleId = role.id;
      getAllPower("rights/tree").then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取权限列表失败！");
        this.allPowerData = res.data;
        // 默认选中的权限
        this.getLeafKeys(role, this.defKeys);
        this.isDistributionPower = true;
      });
    },
    //分配权限提交
    submitDistributionPower() {
      const key = [
        ...this.$refs.treeCheckdRef.getCheckedKeys(),
        ...this.$refs.treeCheckdRef.getHalfCheckedKeys(),
      ];
      const idStr = key.join(",");
      putDistributionPower(`roles/${this.roleId}/rights`, { rids: idStr }).then(
        (res) => {
          if (res.meta.status != 200)
            return this.$message.error("分配权限失败！");
          this.$message.success("分配权限成功！");
          this.getRolesListFile();
          this.isDistributionPower = false;
        }
      );
    },
    //获取默认选中的数据
    getLeafKeys(node, arr) {
      // 传入一个节点，还有一个数组
      if (!node.children) {
        // 判断这个给节点是否有children，没有就是第三级权限，直接加入到arr中
        return arr.push(node.id);
      }
      // 如果没有，继续执行循环
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    addRolesClose() {
      this.$refs.rolesInfoRef.resetFields();
    },
    editRolesClose() {
      this.$refs.editRolesInfoRef.resetFields();
    },
    // 分配权限关闭事件
    distributionPowerClose() {
      this.defKeys = [];
      // 取消时清空默认权限数组数据
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getRolesListFile();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.el-breadcrumb {
  font-size: 16px;
  margin-bottom: 20px;
}
.el-card {
  .add_roles {
    margin-bottom: 20px;
  }
}
.el-row {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 10px 5px;
}
.bottom_border {
  border-bottom: 1px solid #e5e5e5;
}
.top_border {
  border-top: 1px solid #e5e5e5;
}
.space_power {
  text-align: center;
}
</style>